/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package socof.wget;

import htmlparser.HtmlParser;
import java.net.MalformedURLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Carlos Pinheiro
 */
public class ParserExecutor implements Runnable
{

    private ResizeableSemaphore rs;

    public ParserExecutor() throws InterruptedException
    {
        this.rs = ParsersBalancers.getInstance().getParsersSemaphore();
        this.rs.acquire();
    }

    @Override
    public void run()
    {
        WebResource wr = ToParseQueue.getInstance().poll();
        if (wr != null)
        {
            System.out.println("Parsing " + wr.getLocalPath() + " ...");
            
            HtmlParser parser = new HtmlParser(wr.getDomain(), WebResource.getBasePath(),
                                                wr.getLocalPath(), WebResource.getMaxLevel());
            parser.parse();
            //List<String> links = parser.getLinks();
            parser.saveFile();
            
            for (String link : parser.getLinks())
            {
                try
                {
                    WebResource w = new WebResource(link);
                    ToDownloadQueue.getInstance().add(w);
                }
                catch (MalformedURLException ex)
                {
                    Logger.getLogger(DownloaderExecutor.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            System.out.println("Parsed " + wr.getLocalPath() + ".");
        }
        
        this.rs.release();
    }
}
